package com.kfm.web.controller.product;

import com.alibaba.druid.util.StringUtils;
import com.kfm.common.domain.entity.ProductImages;
import com.kfm.common.domain.response.Result;
import com.kfm.common.domain.entity.Product;
import com.kfm.common.exception.ServerException;
import com.kfm.common.util.Constant;
import com.kfm.common.util.SecurityUtils;
import com.kfm.product.service.ProductImagesService;
import com.kfm.product.service.ProductService;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Resource
    private ProductService productService;

    @Resource
    private ProductImagesService productImagesService;

    @Value("${file.upload.path}")
    private String uploadPath;

    @RequestMapping("/list")
    @PreAuthorize("hasAnyAuthority('product:list') or hasAnyRole('ROLE_admin')")
    public Result list(Product product) {
        List<Product> list = productService.selectByCondition(product);
        return list.isEmpty() ? Result.failure("查询失败") : Result.success("查询成功", list);
    }

    /**
     * 查询商品图片
     *
     * @param id 商品编号
     * @return
     */
    @GetMapping("/list/images/{id}")
    @PreAuthorize("hasAnyAuthority('product:list') or hasAnyRole('ROLE_admin')")
    public Result imgList(@PathVariable("id") Integer id) {
        List<ProductImages> list = productImagesService.findByProductId(id);
        return list.isEmpty() ? Result.failure("查询失败") : Result.success("查询成功", list);
    }

    @PostMapping("/edit")
    @PreAuthorize("hasAnyAuthority('product:edit') or hasAnyRole('ROLE_admin')")
    public Result edit(@RequestBody Product product) {
        int i = productService.updateByPrimaryKeySelective(product);
        return i == 0 ? Result.failure("修改失败") : Result.success("修改成功");
    }

    @GetMapping("/delete/{id}")
    @PreAuthorize("hasAnyAuthority('product:delete') or hasAnyRole('ROLE_admin')")
    public Result remove(@PathVariable("id") Integer id) {
        int i = productService.deleteByPrimaryKey(id);
        return i == 0 ? Result.failure("删除失败") : Result.success("删除成功");
    }

    @PostMapping("/add")
    @PreAuthorize("hasAnyAuthority('product:add') or hasAnyRole('ROLE_admin')")
    public Result insert(@RequestBody Product product) {
        int i = productService.insertSelective(product);
        return i == 0 ? Result.failure("新增失败") : Result.success("新增成功");
    }

    @PostMapping("/upload")
    @PreAuthorize("hasAnyAuthority('file:upload') or hasAnyRole('ROLE_admin')")
    public Result upload(MultipartFile file, Integer productId, String name, Byte isPrimary) {
        String oName = file.getOriginalFilename(); // 获取上传图片的原始名称
        if (oName == null || oName.isEmpty()) {
            return Result.failure("请选择文件");
        }
        // 如果没有输入名称或输入的名称为空，就用图片原来的名字
        name = name == null || name.isEmpty() ? oName : name + oName.substring(oName.lastIndexOf('.'));
        try {
            File target = new File(uploadPath, String.valueOf(productId));
            if (!target.exists()) {
                if (!target.mkdirs()) { // 创建文件夹
                    return Result.failure("图片上传失败");
                }
            }
            file.transferTo(new File(target, name));
            ProductImages productImages = new ProductImages();
            productImages.setProductId(productId);
            // 构建图片的 url
            productImages.setImageUrl(Constant.PRODUCT_IMAGE_PRE + productId + File.separator + name);
            productImages.setCreator(SecurityUtils.getUser().getUsername());
            // 是否是主图
            productImages.setIsPrimary(isPrimary == null ? 0 : isPrimary);
            int i = productImagesService.insertSelective(productImages);
            return i > 0 ? Result.success("图片上传成功") : Result.failure("图片上传失败");
        } catch (IOException | MaxUploadSizeExceededException e) {
            if (e instanceof MaxUploadSizeExceededException) {
                throw new ServerException("文件大小不超过10MB", 500);
            }
            return Result.failure("图片上传失败");
        }
    }

    /**
     * 按照图片编号删除图片
     *
     * @param imageId 图片编号
     * @return Result
     */
    @RequestMapping("/delete/image/{id}")
    @PreAuthorize("hasAnyAuthority('file:delete') or hasAnyRole('ROLE_admin')")
    public Result deleteImage(@PathVariable("id") Integer imageId) {
        int i = productImagesService.deleteByPrimaryKey(imageId);
        return i == 0 ? Result.failure("删除失败") : Result.success("删除成功");
    }

    /**
     * 修改商品的主图
     *
     * @return
     */
    @RequestMapping("/edit/image/primary/{pid}/{id}")
    @PreAuthorize("hasAnyAuthority('file:edit') or hasAnyRole('ROLE_admin')")
    public Result editPrimary(@PathVariable("pid") Integer pid, @PathVariable("id") Integer id) {
        int i = productImagesService.updatePrimary(pid, id);
        return i == 0 ? Result.failure("设置失败") : Result.success("设置成功");
    }
}
